package com.dongdongshop.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.dongdongshop.mapper.*;
import com.dongdongshop.pojo.*;
import com.dongdongshop.service.UserService;
import com.dongdongshop.utils.RedisKey;
import com.dongdongshop.utils.ShiroUtils;
import com.dongdongshop.utils.ToEmail;
import com.dongdongshop.vo.AddressVo;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.thymeleaf.util.ArrayUtils;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
@DubboService
public class UserServiceImpl implements UserService {

    @Resource
    private TbUserMapper userMapper;

    @Resource
    private TbAddressMapper addressMapper;
    @Resource
    private TbProvincesMapper provincesMapper;
    @Resource
    private TbCitiesMapper citiesMapper;
    @Resource
    private TbAreasMapper areasMapper;

    @Resource
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    private StringRedisTemplate redisTemplate;

    //查询有没有该用户
    @Override
    public TbUser getUserList(String username) {

        redisTemplate.opsForValue().set(RedisKey.USERNAME, username);

        TbUserExample example = new TbUserExample();
        TbUserExample.Criteria criteria = example.createCriteria();
        criteria.andUsernameEqualTo(username);
        List<TbUser> tbUsers = userMapper.selectByExample(example);
        if (tbUsers.size() > 0) {
            return tbUsers.get(0);
        }
        return null;
    }

    //获取用户地址信息
    @Override
    public List<AddressVo> getAddress(String username) {
        //获取用户id
        //String username = redisTemplate.opsForValue().get(RedisKey.USERNAME);

        return addressMapper.getAddress(username);
    }

    //查询省
    @Override
    public List<TbProvinces> getProvince(String id) {
        TbProvincesExample provincesExample = new TbProvincesExample();
        if (!id.equals("0") && !"".equals(id)) {
            TbProvincesExample.Criteria criteria = provincesExample.createCriteria();
            criteria.andProvinceidEqualTo(id);
        }
        return provincesMapper.selectByExample(provincesExample);
    }

    //获取市
    @Override
    public List<TbCities> getCity(String id) {
        TbCitiesExample citiesExample = new TbCitiesExample();
        if (!id.equals("0") && !"".equals(id)) {
            TbCitiesExample.Criteria criteria = citiesExample.createCriteria();
            criteria.andProvinceidEqualTo(id);
        }
        return citiesMapper.selectByExample(citiesExample);
    }

    //获取区
    @Override
    public List<TbAreas> getDistrict(String id) {
        TbAreasExample areasExample = new TbAreasExample();
        if (!id.equals("0") && !"".equals(id)) {
            TbAreasExample.Criteria criteria = areasExample.createCriteria();
            criteria.andCityidEqualTo(id);
        }
        return areasMapper.selectByExample(areasExample);
    }

    //增加地址信息
    @Override
    public void addAddress(TbAddress address) {
        address.setUserId(redisTemplate.opsForValue().get(RedisKey.USERNAME));
        addressMapper.insertSelective(address);
    }

    //删除地址信息
    @Override
    public void deleteAddress(Long id) {
        addressMapper.deleteByPrimaryKey(id);
    }

    //回显地址信息
    @Override
    public TbAddress editAddress(Long id) {
        return addressMapper.selectByPrimaryKey(id);
    }

    //修改信息
    @Override
    public void updateAddress(TbAddress address) {
        addressMapper.updateByPrimaryKeySelective(address);
    }

    //根据登录 用户名称修改密码,发送邮件
    @Override
    public void updatePwd(String username) {
        TbUser userList = getUserList(username);
        // 获取该用户的邮箱地址
        String email = userList.getEmail();
        // 生成随机密码
        String code = RandomUtil.randomNumbers(4);
        String salt = ShiroUtils.generateSalt(6); //生成盐
        userList.setSalt(salt); // 设置盐
        userList.setPassword(ShiroUtils.encryptPassword("MD5", code, salt, 3)); // 设置加密后密码

        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String format = sdf.format(date);
        StringBuilder sb = new StringBuilder();
        sb.append("您好!<br>");
        sb.append("您在");
        sb.append(format);
        sb.append("提交了重置密码请求。<br>");
        sb.append("您已经成功重置密码了！<br>");
        sb.append("新密码为:<h1>");
        sb.append(code);
        sb.append("</h1><br>");
        sb.append("为了您的帐号安全，请设置登录密码时注意以下几点：<br>");
        sb.append("① 密码不要设置过于简单，像123456、000000、123123这类过于简单的密码很容易被猜到导致帐号被盗；<br>");
        sb.append("② 尽量设置没有规律但自己容易记住的数字字母组合作为密码，密码长度可以根据自己方便记忆设置；<br>");
        sb.append("③ 密码作为私密的信息请勿泄露给其他人，以免帐号被盗造成不必要的损失");
        String content = sb.toString();

        userMapper.updateByPrimaryKeySelective(userList);
        // 密码修改完成之后调用 发送邮件接口发送新密码到用户邮箱中
        ToEmail toEmail = new ToEmail(new String[]{email},
                userList.getUsername() + "您好!"
                , content);


        sendFileEmail(toEmail, null);
    }

    @Override
    public void sendFileEmail(ToEmail toEmail, MultipartFile[] multipartFile) {
        //创建一个MINE消息
        MimeMessage message = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            //谁发
            helper.setFrom(from);
            //谁接收
            helper.setTo(toEmail.getTos());
            //邮件主题
            helper.setSubject(toEmail.getSubject());
            //邮件内容   true 表示带有附件或html
            helper.setText(toEmail.getContent(), true);
            if (ArrayUtils.isEmpty(multipartFile)) {
                for (MultipartFile multiFile : multipartFile) {
                    File multipartFileToFile = MultipartFileToFile(multiFile);
                    FileSystemResource file = new FileSystemResource(multipartFileToFile);
                    String filename = file.getFilename();
                    //添加附件
                    helper.addAttachment(filename, file);
                }
            }
            javaMailSender.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    private File MultipartFileToFile(MultipartFile multipartFile) {
        String path = "E:\\upload\\email\\";
        // 获取文件名
        String fileName = multipartFile.getOriginalFilename();
        // 获取文件后缀
        String prefix = fileName.substring(fileName.lastIndexOf("."));
        // 若需要防止生成的临时文件重复,可以在文件名后添加随机码
        try {
            File file = new File(path + fileName + prefix);
            //File file = File.createTempFile(fileName, prefix);
            multipartFile.transferTo(file);
            return file;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<TbUser> getAll() {
        return userMapper.selectByExample(null);
    }
}
